package com.gyms.adapter;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.classic.okhttp.RequestBeans.HVAddProductOrderListRequestBean;
import com.classic.okhttp.beans.HVAddOrderBean;
import com.classic.okhttp.beans.HVProductTypeItemBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IOrderService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.activity.CodeLoginActivity;
import com.gyms.activity.OrderDetailActivity;
import com.gyms.activity.ProductDetailsActivity;
import com.gyms.base.BaseActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.DataCenter;
import com.gyms.view.bottomview.ScheduleDialog;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import utils.DateUtil;
import utils.DecimalUtils;
import utils.StringUtils;
import weight.ExpandableTextView;

/**
 * 产品详情适配器
 * Created by yjl on 2016/11/16
 */

public class ProductDetailsAdapter extends BaseAdapter {
    private Context mContext;
    private List<HVProductTypeItemBean> mListData;
    private Dialog loadingView;
    private DoProductMustPay mDoProductMustPay;
    private ProductDetailsActivity mProductDetailsActivity;

    public ProductDetailsAdapter(Context mContext, List<HVProductTypeItemBean> mListData, Dialog loadingView) {
        this.mContext = mContext;
        mProductDetailsActivity= (ProductDetailsActivity) mContext;
        this.mListData = mListData;
        this.loadingView = loadingView;
    }
    public void setDoProductMustPay(DoProductMustPay mDoProductMustPay){
        this.mDoProductMustPay=mDoProductMustPay;
    }

    /**
     * 已有订单必须先付款
     */

    public interface DoProductMustPay{
        void goIsProductPay(String mNoPayOrderId,int mNopayOrderType);
    }

    @Override
    public int getCount() {
        return null != mListData ? mListData.size() : 0;
    }

    @Override
    public HVProductTypeItemBean getItem(int position) {
        return mListData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_product, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
            //对于listview，注意添加这一行，即可在item上使用高度
            AutoUtils.autoSize(convertView);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //添加删除线
        holder.tvOldPrise.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        initData(getItem(position), holder,position);
        return convertView;
    }
    private SparseBooleanArray sparseBooleanArray = new SparseBooleanArray();
    private void initData(HVProductTypeItemBean bean, ViewHolder holder,int position) {
        if (!StringUtils.isNull(bean)) {
            holder.tvBtnBuy.setTag(R.id.activity_gym_detail, bean);
            holder.tvBtnBuy.setOnClickListener(showClick);
            if (!StringUtils.isNull(bean.getDesc())) {
                holder.llayoutHaveDetail.setVisibility(View.VISIBLE);
                holder.tvNoticeMore.setText(bean.getDesc(),sparseBooleanArray,position);
            } else {
                holder.llayoutHaveDetail.setVisibility(View.GONE);
            }
            holder.tvCardName.setText(StringUtils.CS(bean.getProductTypeName()));
//            holder.tvNewPrise.setText("￥" + DecimalUtils.doubleToIntOrD(bean.getDiscountPrice()));
            holder.tvNewPrise.setText(DecimalUtils.setPriceStyle(mContext,bean.getDiscountPrice(),R.dimen.price_text_size_14,R.dimen.price_text_size_12,true));
//            holder.tvOldPrise.setText("￥" + DecimalUtils.doubleToIntOrD(bean.getOriginalPrice()));
            holder.tvOldPrise.setText(DecimalUtils.setPriceStyle(mContext,bean.getOriginalPrice(),R.dimen.price_text_size_14,R.dimen.price_text_size_12,true));
        }
    }

    ScheduleDialog dialogs;
    View.OnClickListener showClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!DataCenter.getInstance().checkIsLogin()){
                ToastUtil.showToast(mContext,"请登录后重试");
                ((BaseActivity)mContext).startActivity(CodeLoginActivity.class,false);
                return;
            }
            HVProductTypeItemBean bean = (HVProductTypeItemBean) v.getTag(R.id.activity_gym_detail);
           boolean isBuyTime=doCheckIsStart(bean);
           if(!isBuyTime){//未开始或者抢购时间过了
               return;
           }
            dialogs = new ScheduleDialog(mContext, R.style.BottomToTopAnim, bean);
//            dialogs.setOnClick(showPay);
            dialogs.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    dialogs.setOnClick(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            addVenueOrder(dialogs.getRequestBean());
                        }
                    });
                }
            });
            dialogs.show();
        }
    };

    /**
     * 判断时间时候开始抢或者结束
     * @param bean 规格的bean
     */

    private boolean doCheckIsStart(HVProductTypeItemBean bean) {
        boolean isBuyTime=true;
        int mStartTime=bean.getPurchaseStartTime();//活动开始时间
        int mEndTime=bean.getPurchaseEndTime();//活动结束时间
        int mCurTimes= DateUtil.getCurTimeS();
        //进行判断
        String isCanBuyStr=DateUtil.isProductBuyTime(mProductDetailsActivity.mCurServiceTime,mProductDetailsActivity.mCurLocationTime,mStartTime,mEndTime,mCurTimes);
        if(!StringUtils.isNull(isCanBuyStr)){
            ToastUtil.showToast(mContext,isCanBuyStr);
            isBuyTime=false;
        }
        return isBuyTime;
    }

    /**
     * 生成订单
     * @param bean 下单的产品bean
     */
    private void addVenueOrder(HVAddProductOrderListRequestBean bean) {
        loadingView.show();
        IOrderService.addOrderV2(((BaseActivity) mContext), Enum.EnumCollect.Product, null, bean, false, new ObjectCallback<HVAddOrderBean>() {
            @Override
            public void onSuccess(HVAddOrderBean response, String message) {
                if (loadingView != null) {
                    loadingView.dismiss();
                }
                if (dialogs != null) {
                    dialogs.dismiss();
                }
                if (!StringUtils.isNull(response)) {
                    String mOrderId = response.getOrderId();
                    Bundle mBundle = new Bundle();
                    mBundle.putString(Constants.FLAG_INTENT_GYM_ORDER_ID, mOrderId);//订单Id
                    mBundle.putString(Constants.FLAG_INTENT_IS_CONFIRM, Constants.FLAG_INTENT_IS_CONFIRM);//标识是确认订单页面
                    mBundle.putInt(Constants.FALG_INTENT_PRODUCT_TAG, Constants.PRODUCT_ORDER_TYPE);//标识是产品订单
                    mBundle.putString(Constants.FALG_INTENT_FROM_PRODUCT, Constants.FALG_INTENT_FROM_PRODUCT);//标识从产品进入
                    mBundle.putInt(Constants.FLAG_INTENT_UNPAY_TYPE,Constants.PRODUCT_ORDER_TYPE);//产品的订单
                    ((BaseActivity) mContext).startActivity(OrderDetailActivity.class, mBundle, false);
                }
            }

            @Override
            public void onErrorT(int code, HVAddOrderBean response, String errorMessage) {
                if (loadingView != null) {
                    loadingView.dismiss();
                }
                if (dialogs != null) {
                    dialogs.dismiss();
                }
                if(!StringUtils.isNull(response)){
                    String mNotPayOrderId=response.getNotPayOrderId();//未支付的订单号
                    int mOrderType=response.getNotPayOrderType().value;//未支付的订单类型
                    if(!StringUtils.isNull(mNotPayOrderId)){//先支付
                        if(!StringUtils.isNull(mDoProductMustPay)){
                            mDoProductMustPay.goIsProductPay(mNotPayOrderId,mOrderType);
                        }
                    }
                }else{
                    ToastUtil.showToast(mContext, errorMessage);
                }
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                ToastUtil.showToast(mContext, "statusCode=" + statusCode);
                if (loadingView != null) {
                    loadingView.dismiss();
                }
                if (dialogs != null) {
                    dialogs.dismiss();
                }
            }
        });
    }
//    View.OnClickListener showPay=new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            PaymentDialog dialog=new PaymentDialog(mContext,R.style.BottomToTopAnim,"30");
//            dialog.show();
//            dialogs.dismiss();
//        }
//    };

    }


    class ViewHolder {
        @BindView(R.id.tv_card_name)
        TextView tvCardName;
        @BindView(R.id.tv_new_prise)
        TextView tvNewPrise;
        @BindView(R.id.tv_old_prise)
        TextView tvOldPrise;
        @BindView(R.id.tv_btn_buy)
        LinearLayout tvBtnBuy;
        @BindView(R.id.expand_text_view)
        ExpandableTextView tvNoticeMore;
        @BindView(R.id.llayout_have_detail)
        LinearLayout llayoutHaveDetail;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }


